package logic

import (
	"context"
	"device-modbus/internal/biz/dao"
	"device-modbus/internal/biz/model"
	"device-modbus/internal/biz/query"
	"github.com/jinzhu/copier"
)

type DeviceForwardRuleLogic struct {
	ctx context.Context
}

func NewDeviceForwardRuleLogic(ctx context.Context) *DeviceForwardRuleLogic {
	return &DeviceForwardRuleLogic{ctx: ctx}
}

func (l *DeviceForwardRuleLogic) Add(req *dao.DeviceForwardRuleAddReq) error {
	role := &model.DeviceForwardRule{}
	if err := copier.Copy(role, req); err != nil {
		return err
	}

	return query.Q.DeviceForwardRule.WithContext(l.ctx).Create(role)

}
func (l *DeviceForwardRuleLogic) Update(req *dao.DeviceForwardRuleUpdateReq) error {
	role := &model.DeviceForwardRule{}
	if err := copier.Copy(role, req); err != nil {
		return err
	}
	return query.Q.DeviceForwardRule.WithContext(l.ctx).Save(role)
}
func (l *DeviceForwardRuleLogic) Del(id string) error {
	rule := &model.DeviceForwardRule{
		ID: id,
	}
	_, err := query.Q.DeviceForwardRule.WithContext(l.ctx).Delete(rule)
	return err
}

// 查询设备转发规则
func (l *DeviceForwardRuleLogic) FindByDeviceId(deviceId string) ([]*model.DeviceForwardRule, error) {
	rule := query.Q.DeviceForwardRule
	rules, err := rule.WithContext(l.ctx).Where(rule.DeviceID.Eq(deviceId)).Find()
	return rules, err
}
